package com.yuncheng.spcyApi.spcy;

import cn.hutool.core.collection.CollectionUtil;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.busService.InitWjjlService;
import com.yuncheng.spcyApi.entity.SpcySqsxBasic;
import com.yuncheng.spcyApi.entity.SpcySqsxJob;
import com.yuncheng.spcyApi.entity.SysFlowNode;
import com.yuncheng.spcyApi.flow.SpcyFlowConstant;
import com.yuncheng.spcyApi.mapper.SpcySqsxBaiscMapper;
import com.yuncheng.spcyApi.mapper.SpcySqsxJobMapper;
import com.yuncheng.spcyApi.mapper.YcSysUserMapper;
import com.yuncheng.spcyApi.spcyService.SpcyHbjcService;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.IpRateLimiterUtils;
import com.yuncheng.spcyApi.utils.StringPatternUtils;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import com.yuncheng.spcyApi.vo.hbjc.BhbSqsxJbxxVo;
import com.yuncheng.spcyApi.vo.hbjc.HbSqsxInitWjmbVo;
import com.yuncheng.spcyApi.vo.hbjc.HbSqsxVo;
import com.yuncheng.spcyApi.vo.sqsx.SqsxHbsxZbrVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hua
 */
@Api(tags = "合并检查接口")
@RestController
@RequestMapping("/api/spzx-spcy/hbjc")
public class SpcyHbjcController {

    @Resource
    private SpcySqsxBaiscMapper spcySqsxBaiscMapper;

    @Resource
    private SpcySqsxJobMapper spcySqsxJobMapper;

    @Resource
    private YcSysUserMapper ycSysUserMapper;

    @Resource
    private SpcyHbjcService spcyHbjcService;

    @Resource
    private InitWjjlService initWjjlService;

    @Log(title = "查询当前事项下相同企业的事项列表")
    @ApiOperation(value = "查询当前事项下相同企业的事项列表")
    @GetMapping("getXtsxHjmcSqsxList")
    public HttpResult getXtsxHjmcSqsxList(@RequestParam(value = "jobid",defaultValue = "") String jobid){
        if (StringUtils.isBlank(jobid)){
            return HttpResult.error("流程参数为空！");
        }

        SpcySqsxJob job = spcySqsxJobMapper.selectFhjmcById(jobid);
        if (job == null){
            return HttpResult.error("没有相匹配的流程数据！");
        }

        List<BhbSqsxJbxxVo> sxList = null;
        List<String> hjList = CollectionUtil.newArrayList(
                SpcyFlowConstant.HJMC_RWSL,
                SpcyFlowConstant.HJMC_CLSC,
                SpcyFlowConstant.HJMC_FAZZ
        );
        if (hjList.contains(job.getFhjmc())){
            hjList.add(SpcyFlowConstant.HJMC_CLSCFH);
            sxList = spcySqsxBaiscMapper.selectQyJtHjSxListBySqsxId(job.getFpid(), hjList);
        }else {
            // 查询当前申请事项下-同一个企业所在相同环节的事项列表
            sxList = spcySqsxBaiscMapper.selectXtqyIndexHjSxListBySqsxId(job.getFpid(), SpcyFlowConstant.HJMC_CLSCFH);
        }

        if (sxList != null && sxList.size() == 1){
            return HttpResultVo.HttpResultList(new ArrayList<>(1));
        }
        return HttpResultVo.HttpResultList(sxList);
    }

    @Log(title = "查询合并申请事项下-被合并申请事项列表")
    @ApiOperation(value = "查询合并申请事项下-被合并申请事项列表")
    @GetMapping(value = "getBhbsqsxList")
    public HttpResult getBhbsqsxList(@RequestParam(value = "sqsxid",defaultValue = "") String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("事项参数！");
        }

        /*List<String> ids = StringPatternUtils.getListByIds(spcySqsxBaiscMapper.selectFhbsxidsById(sqsxid));
        return HttpResultVo.HttpResultList(spcySqsxBaiscMapper.selectBhbsqsxListByIds(ids));*/
        return HttpResultVo.HttpResultList(spcySqsxBaiscMapper.selectBhbsqsxListByFhbsxid(sqsxid));
    }

    @Log(title = "查询事项信息-通过被合并事项id")
    @ApiOperation(value = "查询事项信息-通过被合并事项id")
    @GetMapping(value = "getSxInfo")
    public HttpResult getSxInfo(@RequestParam(value = "sqsxid",defaultValue = "SQSXID") String sqsxid){

        return HttpResult.ok(spcySqsxBaiscMapper.selectById(sqsxid));
    }

    @Log(title = "查询合并申请事项下所有的子事项详情列表")
    @ApiOperation(value = "查询合并申请事项下所有的子事项详情列表")
    @GetMapping(value = "queryHbzsxList")
    public HttpResult queryHbzsxList(@RequestParam(value = "sqsxid",defaultValue = "") String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("事项参数！");
        }

        return HttpResultVo.HttpResultList(spcySqsxBaiscMapper.selectBhbsxXqListByIds(sqsxid));
    }

    @Log(title = "合并事项报告模板选择绑定事项-查询被合并事项列表")
    @ApiOperation(value = "合并事项报告模板选择绑定事项-查询被合并事项列表")
    @GetMapping(value = "queryBgBhbsxList")
    public HttpResult queryBgBhbsxList(@RequestParam(value = "sqsxid",defaultValue = "") String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("事项参数为空！");
        }

        return spcyHbjcService.queryBgBhbsxList(sqsxid);
    }



    @Log(title = "查询当前勾选事项的经办人")
    @ApiOperation(value = "查询当前勾选事项的经办人")
    @GetMapping(value = "getdqsxjbrList")
    public HttpResult getDqsxjbrList(@RequestParam(value = "ids",defaultValue = "")String sqsxids){
        if (StringUtils.isBlank(sqsxids)){
            return HttpResult.ok();
        }

        /** 各事项主办人去重 */
        List<String> list = spcySqsxBaiscMapper.selectFzbrIdsListByIds(StringPatternUtils.getListByIds(sqsxids));
        List<String> userIdsList = new ArrayList<>();
        for (String ids : list){
            for (String id : StringPatternUtils.getListByIds(ids)){
                if (!userIdsList.contains(id)){
                    userIdsList.add(id);
                }
            }
        }

        return HttpResultVo.HttpResultList(ycSysUserMapper.findRealnameListsByIds(userIdsList));
    }

    @Log(title = "验证当前人员是否为申请事项的经办人(0：不是经办人/1: 是经办人)")
    @ApiOperation(value = "验证当前人员是否为申请事项的经办人(0：不是经办人/1: 是经办人)")
    @GetMapping(value = "verifySxJbr")
    public HttpResult verifySxJbr(@RequestParam(value = "sqsxid",defaultValue = "") String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("事项参数为空！");
        }

        if (CollectionUtil.isNotEmpty(
                spcySqsxBaiscMapper.selectSxByIdAndFzbr(sqsxid, GetCurrentUserUtils.getCurrentUserId())
        )){
            return HttpResultVo.HttpResultSave("1");
        }
        return HttpResultVo.HttpResultSave("0");
    }

    /*@Log(title = "合并申请事项")
    @ApiOperation(value = "合并申请事项")
    @PostMapping("hbsqsx")*/
    public HttpResult Oldhbsqsx(@RequestBody HbSqsxVo param){

        if (StringUtils.isBlank(param.getIds())){
            return HttpResult.error("请选择被合并事项！");
        }

        if (StringUtils.isBlank(param.getJobid())){
            return HttpResult.error("流程任务参数为空！");
        }
        if (StringUtils.isBlank(param.getZbrid())){
            return HttpResult.error("主办人参数为空！");
        }
        /*if (StringUtils.isBlank(param.getXbrid())){
            return HttpResult.error("协办人参数为空！");
        }*/

        SpcySqsxJob job = spcySqsxJobMapper.selectFhjmcById(param.getJobid());
        if (job == null){
            return HttpResult.error("没有相匹配的流程数据！");
        }

        // 当前发起合并事项的申请事项
        SpcySqsxBasic nowSqsx = spcySqsxBaiscMapper.selectSqsxById(job.getFpid());
        if (nowSqsx == null){
            return HttpResult.error("没有相匹配的事项数据！");
        }

        // 指定方案环节
        SysFlowNode flowNodeInFazz = spcyHbjcService.getFlowNodeInFazz(nowSqsx.getFywflcode());
        if (flowNodeInFazz == null){
            return HttpResult.error("没有相匹配的流程结点配置！");
        }

        // 获取被合并事项的事项名称
        List<String> idsList = new ArrayList<>();
        idsList.add(job.getFpid()); // 当前流程对应的事项
        idsList.addAll(StringPatternUtils.getListByIds(param.getIds()));

        List<String> sxmcList = spcySqsxBaiscMapper.selectFsxmcListByIds(idsList);
        String hbsxmc = ""; // 最新合并的事项名称
        for (String b : sxmcList){
            if (StringUtils.isNotBlank(hbsxmc)){
                hbsxmc += "/";
            }
            hbsxmc += b;
        }

        /** 获取所有主办人 */
        /*List<SqsxZbrVo> hbsxZbrList = spcySqsxBaiscMapper.selectFzbrListByIds(idsList);
        if (CollectionUtil.isNotEmpty(hbsxZbrList)){
            for (SqsxZbrVo zbrVo : hbsxZbrList){

            }
        }*/

        // 主办人、协办人
        param.setZbrid(StringPatternUtils.getStringsByIds(param.getZbrid())[0]);
        param.setXbrid(StringPatternUtils.getStringsByIds(param.getXbrid())[0]);

        String dbrid = param.getZbrid() + "," + param.getXbrid();
        spcyHbjcService.hbsqsx(idsList,
                job, nowSqsx,
                hbsxmc, "", "", "",
                param, dbrid, flowNodeInFazz);

        return HttpResult.ok("操作成功");
    }

    @Log(title = "合并申请事项")
    @ApiOperation(value = "合并申请事项")
    @PostMapping("hbsqsx")
    public HttpResult newHbsx(@RequestBody HbSqsxVo param){
        // 接口限流
        if (!IpRateLimiterUtils.tryAcquire(GetCurrentUserUtils.getCurrentUserId())){
            return HttpResult.error("访问过于频繁，请稍候再试！");
        }

        if (StringUtils.isBlank(param.getIds())){
            return HttpResult.error("请选择被合并事项！");
        }

        if (StringUtils.isBlank(param.getJobid())){
            return HttpResult.error("流程任务参数为空！");
        }
        if (StringUtils.isBlank(param.getZbrid())){
            return HttpResult.error("主办人参数为空！");
        }
        if (StringUtils.isBlank(param.getOpinion())){
            return HttpResult.error("意见为空！");
        }

        // 被合并事项ids
        List<String> idsList = StringPatternUtils.getListByIds(param.getIds());

        if (idsList.size() == 1){
            return HttpResult.error("请选择至少两个件进行合并！");
        }

        // 查询当前流程名称
        SpcySqsxJob job = spcySqsxJobMapper.selectFhjmcById(param.getJobid());
        if (job == null){
            return HttpResult.error("没有相匹配的流程数据！");
        }

        // 当前发起合并事项的申请事项
        SpcySqsxBasic nowSqsx = spcySqsxBaiscMapper.selectById(idsList.get(0));
        if (nowSqsx == null){
            return HttpResult.error("没有相匹配的事项数据！");
        }

        // 指定方案环节
        SysFlowNode flowNodeInFazz = spcyHbjcService.getFlowNodeInFazz(nowSqsx.getFywflcode());
        if (flowNodeInFazz == null){
            return HttpResult.error("没有相匹配的流程结点配置！");
        }

        String hbsxmc = ""; // 最新合并的事项名称
        String hbslbh = "";
        String hbjclx = "";
        String hbsqdbh = "";
        String xbrids = ""; // 协办人id

        /** 查询被合并事项的基本信息 */
        List<String> existsHbsqIdList = new ArrayList<>();
        List<SqsxHbsxZbrVo> hbsxZbrList = new ArrayList<>();
        for (String bhbsxid : idsList){

            /** 排除重复的数据id */
            if (StringUtils.isBlank(bhbsxid) || existsHbsqIdList.contains(bhbsxid)) {
                continue;
            }

            SqsxHbsxZbrVo zbrVo = spcySqsxBaiscMapper.selectFzbrVoById(bhbsxid);
            if (zbrVo != null) {
                hbsxZbrList.add(zbrVo);
                existsHbsqIdList.add(bhbsxid);
            }
        }

        if (CollectionUtil.isEmpty(hbsxZbrList)){
            return HttpResult.error("没有相匹配的数据！");
        }

        for (SqsxHbsxZbrVo zbrVo : hbsxZbrList){
            if (StringUtils.isBlank(zbrVo.getFzbr())){
                return HttpResult.error("操作失败，"+zbrVo.getFsxmc()+"没有选择经办人，不满足合并要求！");
            }

            /** 各被合并事项拼接为协办人ids */
            if (zbrVo.getFzbr().contains(",")){
                for (String id : StringPatternUtils.getListByIds(zbrVo.getFzbr())){
                    if (StringUtils.isNotBlank(xbrids)) {
                        if (!xbrids.contains(id)) {
                            xbrids += "," + id;
                        }
                    }else {
                        xbrids += id;
                    }
                }
            }else {
                if (StringUtils.isNotBlank(xbrids)) {
                    if (!xbrids.contains(zbrVo.getFzbr())) {
                        xbrids += "," + zbrVo.getFzbr();
                    }
                }else {
                    xbrids += zbrVo.getFzbr();
                }
            }

            hbsxmc += StringUtils.isNotBlank(hbsxmc) ? "、" : "";
            hbsxmc += zbrVo.getFsxmc();

            if (StringUtils.isNotBlank(zbrVo.getFslbh())) {
                hbslbh += StringUtils.isNotBlank(hbslbh) ? "、" : "";
                hbslbh += zbrVo.getFslbh();
            }

            if (StringUtils.isNotBlank(zbrVo.getFjclx())) {
                hbjclx += StringUtils.isNotBlank(hbjclx) ? "、" : "";
                hbjclx += zbrVo.getFjclx();
            }

            if (StringUtils.isNotBlank(zbrVo.getFsqdbh())) {
                hbsqdbh += StringUtils.isNotBlank(hbsqdbh) ? "、" : "";
                hbsqdbh += zbrVo.getFsqdbh();
            }
        }

        // 合并事项名称
        if (StringUtils.isNotBlank(param.getHbsxmc())){
            hbsxmc = param.getHbsxmc();
        }

        // 主办人、协办人
        param.setZbrid(StringPatternUtils.getStringsByIds(param.getZbrid())[0]);
        param.setXbrid(xbrids);

        String dbrid = xbrids;

        /** 合并事项处理 */
        spcyHbjcService.hbsqsx(idsList,
                job, nowSqsx,
                hbsxmc, hbslbh, hbjclx, hbsqdbh,
                param, dbrid, flowNodeInFazz);

        return HttpResult.ok();
    }


    @Log(title = "删除并上传申请事项文件")
    @ApiOperation(value = "删除并上传申请事项文件")
    @PostMapping(value = "deletUploadSqsxFile")
    public HttpResult deletUploadSqsxFile(@RequestPart("file") MultipartFile[] uploadFile,
                                          @RequestParam(value = "fileid",defaultValue = "") String fileid){

        initWjjlService.replaceUploadSqsxFile(uploadFile,fileid,true,true);
        return HttpResult.ok("上传成功");
    }

    @Log(title = "事项文件删除并上传")
    @ApiOperation(value = "事项文件删除并上传")
    @PostMapping(value = "delScSxFile")
    public HttpResult delScSxFile(@RequestPart("file") MultipartFile[] uploadFile,
                                  @RequestParam(value = "sqsxid",defaultValue = "") String sqsxid,
                                  @RequestParam(value = "type",defaultValue = "") String type){

        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("事项参数为空！");
        }

        if (StringUtils.isBlank(type)){
            return HttpResult.error("请选择要上传的文件类型！");
        }

        initWjjlService.deleteUploadSqsxFile(uploadFile, sqsxid, type, "",false);
        return HttpResult.ok("上传成功");
    }

    @Log(title = "合并事项-上传被合并事项相关文件")
    @ApiOperation(value = "合并事项-上传被合并事项相关文件")
    @PostMapping(value = "uploadHbFile")
    public HttpResult uploadHbFile(@RequestPart("file") MultipartFile[] uploadFile,
                                   @RequestParam(value = "sqsxid",defaultValue = "") String sqsxid,
                                   @RequestParam(value = "type",defaultValue = "") String type){

        if (uploadFile == null || uploadFile.length == 0) {
            return HttpResult.error("上传失败,请先选择文件！");
        }

        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("事项参数为空！");
        }

        if (StringUtils.isBlank(type)){
            return HttpResult.error("请选择要上传的文件类型！");
        }

        initWjjlService.uploadSqsxFile(uploadFile, sqsxid, type,false);

        return HttpResult.ok("上传成功");
    }

    @Log(title = "初始化合并事项-文件记录")
    @ApiOperation(value = "初始化合并事项-文件记录")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "sqsxid",value = "申请事项id",required = true),
            @ApiImplicitParam(name = "type",value = "模板类型",required = true),
            @ApiImplicitParam(name = "id",value = "文件模板id",required = true),
            @ApiImplicitParam(name = "ids",value = "被合并申请事项ids",required = true)
    })
    @PostMapping(value = "initHbsqsxWjjl")
    public HttpResult<?> initHbsqsxWjjl(@RequestBody HbSqsxInitWjmbVo param) {
        if (StringUtils.isBlank(param.getSqsxid())){
            return HttpResult.error("事项参数为空！");
        }
        if (StringUtils.isBlank(param.getId())) {
            if (StringUtils.isBlank(param.getType())) {
                return HttpResult.error("模板类型参数为空！");
            }
        }

        spcyHbjcService.initHbsxWjjl(param.getSqsxid(), param.getType(), param.getId(), param.getIds());

        return HttpResult.ok("操作成功");
    }

}
